<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'common/config.php';
require_once 'common/functions.php';

// 启动会话并检查登录状态
session_start();
check_login();

// 权限验证（仅超级管理员可操作）
if ($_SESSION['role'] != 1) {
    die(json_encode([
        'success' => false,
        'message' => '权限不足！'
    ]));
}

// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    die(json_encode([
        'success' => false,
        'message' => '仅支持POST请求'
    ]));
}

// 获取并验证ID参数
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
if ($id <= 0) {
    die(json_encode([
        'success' => false,
        'message' => '无效的管理员ID'
    ]));
}

// 防止删除当前登录账号
if ($id == $_SESSION['user_id']) {
    die(json_encode([
        'success' => false,
        'message' => '不能删除当前登录账号'
    ]));
}

try {
    $db = db_connect();
    
    // 获取管理员信息
    $stmt = $db->prepare("SELECT avatar FROM admin_users WHERE id = ?");
    $stmt->execute([$id]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$admin) {
        die(json_encode([
            'success' => false,
            'message' => '管理员不存在'
        ]));
    }

    // 删除头像文件
    if (!empty($admin['avatar'])) {
        $avatar_path = '../api/user/' . $admin['avatar'];
        if (file_exists($avatar_path)) {
            unlink($avatar_path);
        }
    }

    // 执行删除操作
    $stmt = $db->prepare("DELETE FROM admin_users WHERE id = ?");
    $stmt->execute([$id]);

    // 返回成功响应
    echo json_encode([
        'success' => true,
        'message' => '管理员删除成功'
    ]);

} catch(Exception $e) {
    die(json_encode([
        'success' => false,
        'message' => '系统错误：' . $e->getMessage()
    ]));
}